﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using BllFactory;
using ETWebApi2.ETWeiXin;
using ETWebApi2.Models;
using IBLL;
using Model;

namespace ETWebApi2.Controllers
{
    
    [Route("partner"), JwtAuthActionFilter]
    public class PartnerController : ApiController
    {
        private IVIEW_PRService m_prSev = ServiceFactory.CreatService<IVIEW_PRService>();
        private ICUser_tbService m_userSev = ServiceFactory.CreatService<ICUser_tbService>();
        private IPartnerRelation_tbService m_Partner = ServiceFactory.CreatService<IPartnerRelation_tbService>();
        private ICustomers_tbService m_cusSev = ServiceFactory.CreatService<ICustomers_tbService>();
        private MyETLockContext m_db = DbContextFactory.GetDbContext();
        private BaseClass m_bc = new BaseClass();

        /// <summary>
        ///  初始化数据/我加了谁(add)   谁加了我(addme) 
        /// </summary> 
        ///  <param name="action">区分操作</param>
        /// <param name="pageindex"></param> 
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetAllPartner(string action,int page, int limit,string STime = null,string ETime = null, string query = "")
        {

            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            int count = 0;
            List<VIEW_PR> pages = new List<VIEW_PR>();
            List<ShowPartner> partners = new List<ShowPartner>();
            if (!string.IsNullOrEmpty(action))
            {               
                if (action == "add")
                {
                    pages = m_prSev.GetListByPage(p => p.SelfCompanyId == info.CurentCopmpanyId && (p.Name.Contains(query) || p.address.Contains(query)), p => p.State, false, page, limit, ref count).OrderByDescending(p=>p.filenum).ToList();
                    if (!string.IsNullOrEmpty(STime) && !string.IsNullOrEmpty(ETime))
                        partners=GetInfoByTime(true,pages, Convert.ToDateTime(STime), Convert.ToDateTime(ETime));
                    else
                        partners = GetInfoByTime(false, pages, DateTime.Now, DateTime.Now);
                }
                else if(action=="addme")
                {
                    pages = m_prSev.GetListByPage(p => p.PartnerId == info.CurentCopmpanyId && p.State == 1, p => p.Time, false, page, limit , ref count);
                    foreach (var p in pages)
                    {
                        ShowPartner partner = new ShowPartner()
                        {
                            Id=p.Id,
                            CompanyId = (int)p.SelfCompanyId,
                            CompanyName = m_bc.GetCompanyName((int)p.SelfCompanyId),
                            CanOpenUser = m_bc.GetMaster(info.CurentCopmpanyId,(int)p.SelfCompanyId), //对方公司设定我能打开文件的人                           
                            FileNum = 0,
                            State = (int)p.State,
                            Address="",
                            Level = p.Level
                        };
                        partners.Add(partner);
                    }
                }                
            }
            HttpResponseMessage result = ObjectToJson.toJson(new {status=200,data=new { total = count, rows =partners }});
            return result;
        }
        private List<ShowPartner> GetInfoByTime(bool isTime,List<VIEW_PR> pages,DateTime STime,DateTime ETime)
        {
            List<ShowPartner> partners = new List<ShowPartner>();            
            foreach (var p in pages)
            {
                ShowPartner partner = new ShowPartner();
                partner.Id = p.Id;
                partner.CompanyId = (int)p.PartnerId;
                partner.CompanyName = p.Name;
                partner.Address = p.address;
                if(isTime)
                    partner.FileNum = CompanyFilesCount((int)p.SelfCompanyId, (int)p.PartnerId, STime, ETime);
                else
                    partner.FileNum = CompanyFilesCount((int)p.SelfCompanyId, (int)p.PartnerId, DateTime.Now.AddMonths(-3), DateTime.Now);
                partner.State = (int)p.State;
                partner.CanOpenUser = "";
                partner.Level = p.Level;

                partners.Add(partner);
            }
            return partners;
        }

        /// <summary>
        /// 寻找伙伴 
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFindPartner(string query)
        {
            //当前登陆者信息 
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            int currentRole = GetCurrentCusIsDeal();
            //出于安全考虑一次只加载6个客户信息 
            HttpResponseMessage result = new HttpResponseMessage();
            if (!string.IsNullOrEmpty(query))
            {
                //string sql = string.Format("select top 6 * from Customers_tb where id!={1} and IsDeal>=10 and (Name like '%{0}%' or address like '%{0}%' or (select count(*) from Locks_tb where customerId=Customers_tb.Id and lockNum='{0}') > 0) order by name", query, info.CurentCopmpanyId);
                string sql = string.Format("select * from Customers_tb where id!={1} and IsDeal>=10 and (Name like '%{0}%' or address like '%{0}%' or (select count(*) from Locks_tb where customerId=Customers_tb.Id and lockNum='{0}') > 0) order by name", query, info.CurentCopmpanyId);
                List<Customers_tb> cList = new List<Customers_tb>();
                using (var context = new MyETLockContext())
                {
                    cList = context.Database.SqlQuery<Customers_tb>(sql).ToList();
                }
                List<Customers_tb> showCus = new List<Customers_tb>();
                foreach (Customers_tb c in cList)
                {
                    PartnerRelation_tb partner = new PartnerRelation_tb();
                    partner = m_Partner.GetList(p => ((p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == c.Id ))).FirstOrDefault();
                    #region 
                    //if (currentRole == 0) //接受方
                    //{
                    //    partner = Partner.GetList(p => ((p.SelfCompanyId == c.Id && p.PartnerId == info.CurentCopmpanyId) || (p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == c.Id))).FirstOrDefault();
                    //}
                    //else
                    //{
                    //    partner = Partner.GetList(p => ((p.SelfCompanyId == c.Id && p.PartnerId == info.CurentCopmpanyId) || (p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == c.Id))).FirstOrDefault();
                    //}
                    #endregion
                    if (partner == null)
                    {
                        showCus.Add(c);
                        if (showCus.Count == 4)
                            break;
                    }
                }
                 result = ObjectToJson.toJson(new { status = 200, data = new { total = 4, rows = showCus } });
            }
            else
            {
                result = ObjectToJson.toJson(new { status = 201, data = new { total = 0, rows = "[]" } });
            }
            return result;
        }

        /// <summary>
        /// 加载合作伙伴的员工名称 故返回员工名字 和相应的id 
        /// </summary> 此函数仅供发单发使用 
        /// <param name="partnerId"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPartnerStaff(int partnerId)
        {
            var ttlist = from cc in m_db.CUser_tb where cc.CompanyId  == partnerId select new { cc.Id ,cc.UserName,cc.Remark};
            return ObjectToJson.toJson(new {status=200,data=new {total=ttlist.Count(),rows=ttlist } });
        }

        /// <summary>
        /// 获取申请者信息  只有发单方有此功能 （因为接单方添加合作伙伴需要发单发的批准（同意） 而发单发添加合作伙时不需要）
        /// </summary>
        [HttpGet]
        public HttpResponseMessage GetApplyPartner(int page,int limit)
        {
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            int count = 0;
            List<PartnerRelation_tb> partners = m_Partner.GetListByPage(p => p.SelfCompanyId == info.CurentCopmpanyId && p.State == 2, p => p.Time, false, page, limit, ref count);
            List<AddPartner> others = new List<AddPartner>();
            foreach (var p in partners)
            {
                Customers_tb cus = m_cusSev.GetList(c=>c.Id==p.PartnerId).FirstOrDefault();
                AddPartner other = new AddPartner() {
                    Id = p.Id,
                    CompanyId = (int)p.PartnerId,
                    CompanyName = cus.Name,
                    Address=cus.address
                };
                others.Add(other);
            }
           return ObjectToJson.toJson(new {status=200,data=new {total=count,rows=others } });
        }

        /// <summary> 
        /// 添加合作伙伴    
        /// </summary> SelfCompanyId  文件发单方客户Id   partnerId文件接收方客户Id
        /// <param name="obj"> pCid合作方的公司Id   touser可以打开文件的员工Id，可以多个 用'|'隔开（针对发单方）   companyName公司名</param>
        [HttpPost]
        public HttpResponseMessage PostAdd(dynamic obj)
        {
            PartnerRelation_tb newPartner = new PartnerRelation_tb();
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            CUser_tb user = m_userSev.GetList(u=>u.Id==info.UserId).FirstOrDefault();
            int PartnerId = Convert.ToInt32(obj.Id);
            //if (GetCurrentCusIsDeal()==0)  //11--》接受方  12-->发单发  接单方发送请求
            //{
            //    return  (AsAcpterToAdd(PartnerId, (int)user.CompanyId, obj.companyName.ToString()) >= 1? ObjectToJson.toJson(new { status = 200, rel = true }): ObjectToJson.toJson(new { status = 201, error = "添加失败" })); 
            //}
            //else  //发单直接添加员工
            //{
                if (m_Partner.GetList(p => p.SelfCompanyId == (int)user.CompanyId && p.State == 1 && p.PartnerId == PartnerId).FirstOrDefault() == null)
                {
                    //if (GetCurrentCusIsDeal() != 0)
                    //{
                    newPartner.SelfCompanyId = (int)user.CompanyId;
                    newPartner.PartnerId = PartnerId;
                    //}
                    //else
                    //{
                    //    newPartner.PartnerId = (int)user.CompanyId;
                    //    newPartner.SelfCompanyId = PartnerId;
                    //}
                    newPartner.touser ="";  //对方可以打开文件的员工 
                    newPartner.Receiver = "";
                    newPartner.State = 1;
                    newPartner.Time = DateTime.Now;
                    if (m_Partner.Add(newPartner))
                    {
                        return ObjectToJson.toJson(new { status = 200, rel = true }); 
                    }
                    else
                    {
                        return ObjectToJson.toJson(new { status = 201, error = "添加失败" });
                    }
                }
                else {
                    return ObjectToJson.toJson(new { status=201,error= "添加失败" });
                }
            //}           
        }

        /// <summary>
        /// 接收方添加合作伙伴 后置需求
        /// </summary>
        /// <param name="pCid"></param>
        /// <param name="selfCid"></param>
        /// <param name="companyName"></param>
        /// <returns></returns>
        private int AsAcpterToAdd(int pCid,int selfCid,string companyName)
        {
            if (m_Partner.GetList(p => p.SelfCompanyId == pCid && p.State == 1 && p.PartnerId == selfCid).FirstOrDefault() == null)
            {
                PartnerRelation_tb newPartner = new PartnerRelation_tb();
                newPartner.SelfCompanyId = pCid;
                newPartner.PartnerId = selfCid;
                newPartner.touser = "";
                newPartner.Receiver = "";
                newPartner.State = 2;
                if (m_Partner.Add(newPartner))
                {
                    //获取对方主管服务号微信 
                    CUser_tb PartnerUser = m_userSev.GetList(u => u.CompanyId == pCid && u.Role == 1).FirstOrDefault();
                    if (PartnerUser == null)                    
                        return 1;   // "对方主管还未关注微信，暂时无法发送微信通知！"; 已成功添加
                    else
                    {
                        //添加微信通知  
                        FwhSendMessage fsm = new FwhSendMessage(HttpContext.Current.Application);
                        //state参数  后操作类型(一个字母表示) id  a---申请 
                        fsm.Send4(PartnerUser.FWH, "JIBYhrkWWqzRcIwzvKSSF-2TTaQoxGKOAQ8OjK0gWx4", "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx06b50ea9b66d73f6&redirect_uri=http%3A%2F%2Fcrm.etsystem.cn%2FFwhApplyInform.aspx&response_type=code&scope=snsapi_base&state=a" + newPartner.Id + "#wechat_redirect", "申请成为合作伙伴", companyName, DateTime.Now.ToString(), "点击此处进入审核界面");
                        fsm.SaveToken(HttpContext.Current.Application);
                        return 2;  //res = "成功申请，并发送微信通知";
                    }
                }
                else
                {
                    return 0; 
                }
            }
            else
            {
                return -1; // 已经是合作伙伴
            }
        }

        /// <summary>
        /// 判断当前客户是接单还是发单
        /// </summary>
        public int GetCurrentCusIsDeal()
        {
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            Customers_tb currentCus = m_cusSev.GetList(c => c.Id == info.CurentCopmpanyId).FirstOrDefault();
            int res = 0;
            if (currentCus.IsDeal == 11)  //接单
            {               
                res = 0;
            }
            else if (currentCus.IsDeal == 12)
            {
                res = 1;
            }
            return res;
        }

        /// <summary>
        /// 停止合作(stop)跟启用合作(start)  处理合作伙伴申请（发单才有的功能）
        /// </summary>提供参数  要执行的状态（禁止 启用）,这条记录id(唯一标识)  
        /// <param name="obj"></param>
        [HttpPut,Route("relation")]
        public HttpResponseMessage Put(dynamic obj)
        {
            int state =Convert.ToInt32(obj.State);
            PartnerRelation_tb Uppartner = m_Partner.GetList(p=>p.Id==Convert.ToInt32(obj.Id)).FirstOrDefault();
            if (state == 1)
            {
                Uppartner.State = 1;
            }
            else if (state == 0)
            {
                Uppartner.State = 0;
            }
            if (m_Partner.Update(Uppartner) == true)
                return ObjectToJson.toJson(new { status = 200, rel = true });
            else
                return ObjectToJson.toJson(new { status = 201, error = "操作出错" });            
        }

        /// <summary>
        /// 文件权限
        /// </summary>提供参数  要执行的状态（禁止 启用）,这条记录id(唯一标识)  
        /// <param name="obj"></param>
        [HttpPut, Route("level")]
        public HttpResponseMessage PutLevel(dynamic obj)
        {
            int Level = Convert.ToInt32(obj.Level);
            PartnerRelation_tb Uppartner = m_Partner.GetList(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
            if(Uppartner==null)
                return ObjectToJson.toJson(new { status = 201, error = "没有找到该公司的相关信息" });
            Uppartner.Level = Level;
            if (m_Partner.Update(Uppartner))
                return ObjectToJson.toJson(new { status = 200, rel = true });
            else
                return ObjectToJson.toJson(new { status = 201, error = "操作出错" });
            
        }

        /// <summary>
        ///  设定可以打开文件的人员（有MAC的有就可以被选择）   我加了谁    
        /// </summary> 
        /// <param name="pid"></param>  
        [HttpGet,Route("add")]
        public HttpResponseMessage SetOtherOpen(string CompanyId)
        {
            List<PartInfo> parts = new List<PartInfo>();
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            if (!string.IsNullOrEmpty(CompanyId.ToString()) && m_bc.CheckNumber(CompanyId))
            {
                string cname = m_cusSev.GetList(c => c.Id == int.Parse(CompanyId)).FirstOrDefault().Name;
                CUser_tb user= m_userSev.GetList(u=>u.Id==info.UserId).FirstOrDefault();
                if (m_bc.isAdmin(user))
                {                    
                    //获取该合作伙伴下有效的员工
                    List<CUser_tb> clist = m_userSev.GetList(u => u.State == 1 && u.CompanyId == int.Parse(CompanyId)).OrderByDescending(u => u.State).ThenByDescending(u => u.Role).ToList();
                    //获取默认能够打开文件的板师   
                    PartnerRelation_tb pRelation = m_Partner.GetList(p => p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == int.Parse(CompanyId)).FirstOrDefault();
                    foreach (CUser_tb c in clist)
                    {                     
                        if (c.MAC!=null && !string.IsNullOrEmpty(c.MAC.Trim()))
                        {
                            bool re = Array.IndexOf(pRelation.touser.Split('|'), c.Id.ToString()) == -1 ? false : true;
                            string Remark = "";
                            if (c.Remark.Length > 0)
                                Remark = "(" + c.Remark + ")";
                            PartInfo part = new PartInfo() { Id = c.Id, Remark = Remark, UserName = c.UserName, IsChecked = re };
                            parts.Add(part);
                        }                        
                    }                    
                }
            }
            if (parts.Count > 0)
            {                
                return ObjectToJson.toJson(new { status=200,data=new {total=parts.Count,rows=parts } });
            }
            else
            {               
                return ObjectToJson.toJson(new {status=201,error= "没有员工绑定MAC" }); // 没有员工绑定MAC
            }
        }

        /// <summary>
        /// 设定本公司可以接收文件的员工(有效且有下载[接受]权限)  谁加了我  
        /// </summary>
        /// <param name="obj">被选中的公司Id，当前选中的员工id 选中的员工可能是多个  前端用‘|’ 分割</param>
        [HttpGet,Route("addme")]
        public  HttpResponseMessage SetSelfAcepteer(string CompanyId)
        {
            List<PartInfo> parts = new List<PartInfo>();
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            if (!string.IsNullOrEmpty(CompanyId) && m_bc.CheckNumber(CompanyId))
            {
               //获取本公司下有效且有下载权限的员工
                List<CUser_tb> clist = m_userSev.GetList(u => u.CompanyId == info.CurentCopmpanyId && u.State == 1 && (u.Down==1 || u.Permission=="01" || u.Permission=="11"));
                PartnerRelation_tb pRelation = m_Partner.GetList(p=>p.PartnerId==info.CurentCopmpanyId && p.SelfCompanyId==int.Parse(CompanyId) && p.State==1).FirstOrDefault();
                if (pRelation == null)
                    return ObjectToJson.toJson("");                
                foreach (CUser_tb c in clist)
                {
                    List<string> infos = new List<string>();
                    bool re = Array.IndexOf(pRelation.Receiver.Split('|'), c.Id.ToString()) == -1 ? false : true;  //用于标记是否已经被选中
                    string Remark = "";
                    if (c.Remark.Length > 0)
                        Remark = "(" + c.Remark + ")";
                    PartInfo part = new PartInfo() { Id = c.Id, Remark = Remark, UserName = c.UserName, IsChecked = re };
                    parts.Add(part);
                }
                if(parts.Count>0)
                   return ObjectToJson.toJson(new { status = 200, data = new { total = parts.Count, rows = parts } });
                else
                   return ObjectToJson.toJson(new { status = 201, error = "没有可接受文件员工" });
            }
            else
            {
                return ObjectToJson.toJson(new { status = 201, error = "没有可接受文件员工" });
            }

        }

        /// <summary>
        /// 统计发给伙伴的文件数量
        /// </summary>    
        /// <param name="selfId"></param>
        /// <param name="partnerId"></param>
        /// <returns></returns>
        private int CompanyFilesCount(int selfId, int partnerId, DateTime STime, DateTime ETime)
        {
            int count = 0;
            var data = (from files in m_db.Files_tb
                        join cuser in m_db.CUser_tb
                        on files.UploadUserId equals cuser.Id
                        select new
                        {
                            FileId=files.Id,
                            PartnerId=files.CompanyId,
                            SelfId=cuser.CompanyId,
                            Time=files.Time,
                            UserId=cuser.Id
                        }).ToList();
            data = data.Where(f=>f.Time>=STime && f.Time<=ETime && f.PartnerId ==partnerId && f.SelfId==selfId).ToList();
            return count=data.Count;
        }
        // 确认  打开文件的员工   接受文件的员工    确认参数 touser 接受人的id可以有多个用‘|’间隔  CompanyId客户id open
        #region 主管设置伙伴公司能打开文件的员工/能接受文件的员工 
        [HttpPut,Route("config")]
        public HttpResponseMessage SetReceiverOrOpen(dynamic obj)
        {
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            string touser = obj.touser;
            string pid = obj.CompanyId;
            //if (touser == "" || string.IsNullOrEmpty(touser))
            //{
            //    //取消选择或者不选                
            //    //return ObjectToJson.toJson(new { status = 201, error = "人员设定不能为空" + touser });
            //}
            //else
            //{ 
                if (!string.IsNullOrEmpty(pid) && m_bc.CheckNumber(pid) && info != null)
                {
                    if (touser.Split('|').Length <9)
                    {
                        PartnerRelation_tb pRelation = new PartnerRelation_tb();
                        if (obj.action == "open")
                        {
                            pRelation = m_Partner.GetList(p => p.SelfCompanyId == info.CurentCopmpanyId && p.PartnerId == int.Parse(pid)).FirstOrDefault();
                            return ChoseConfirm(pRelation, touser, obj.action.ToString());
                        }
                        else
                        {
                            pRelation = m_Partner.GetList(p => p.SelfCompanyId == int.Parse(pid) && p.PartnerId == info.CurentCopmpanyId).FirstOrDefault();
                            return ChoseConfirm(pRelation, touser, obj.action.ToString());
                        }
                    }
                    else
                    {
                        return ObjectToJson.toJson(new { status = 201, error = "选定的人数超过7人，本次提交失败" });
                    }
                }
            //}
            return ObjectToJson.toJson(new { status = 201, error = "信息有误" });

        }
        #endregion
        private HttpResponseMessage ChoseConfirm(PartnerRelation_tb pRelation, string touser,string action)
        {
            if (pRelation == null)
                return ObjectToJson.toJson(new { status = 201, error = "指定伙伴不存在" });
            if (action == "open")
                pRelation.touser = touser.Substring(0,touser.Length-1);
            else
                pRelation.Receiver = touser.Substring(0, touser.Length - 1);
            if (m_Partner.Update(pRelation))
                return ObjectToJson.toJson(new { status = 200, rel = true });            
            else
                return ObjectToJson.toJson(new { status = 201, error = "指定失败" });

        }
    }
}
